package com.syl.practice.globalexception.common.aspect;

import com.syl.practice.globalexception.enums.ApiEnum;
import com.syl.practice.globalexception.exception.ApiException;
import com.syl.practice.globalexception.result.ApiResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * 切面2
 * order设置为20 （order越大，越后执行）
 * 后执行
 */
@Aspect
@Component
public class GlobalExceptionHandler2 implements Ordered {

    /**
     * @Controller或@RestController中返回ApiResult的任意方法
     */
    @Pointcut("(@within(org.springframework.stereotype.Controller)||@within(org.springframework.web.bind.annotation.RestController)) && execution(public com.syl.practice.globalexception.result.ApiResult *(..))")
    public void exc() {
    }

    @Around("exc()")
    public ApiResult handleResult(ProceedingJoinPoint point) {
        try {
            return (ApiResult) point.proceed();
        } catch (Throwable e) {
            return hanldeException(e);
        }
    }

    private ApiResult hanldeException(Throwable e) {
        if (e instanceof ApiException) {
            return new ApiResult((ApiException) e);
        }
        return new ApiResult(new ApiException(ApiEnum.ERROR));
    }

    @Override
    public int getOrder() {
        return 20;
    }
}
